    //
    //  SRLoginManager.m
    //  EnglishTalk
    //
    //  Created by CyonLeuPro on 15/6/9.
    //  Copyright (c) 2015年 Feizhu Tech. All rights reserved.
    //

#import "SRLoginManager.h"
#import <OpenUDID.h>
#import "FCUtil.h"
#import <NSString+Enhanced.h>
#import "FZNavigationController.h"
#import "AppDelegate.h"
#import <JPush/JPUSHService.h>
//#import "FZPersonCenterService.h"

@interface SRLoginManager ()
    //@property (strong, nonatomic) SRLoginUser *currentUser;

@property (strong, nonatomic) TencentOAuth *tencentOAuth;
@property (strong, nonatomic) FZLoginViewController *loginViewController;

@property (copy, nonatomic) FZLoginSuccessBlock loginSuccessBlock;
@property (copy, nonatomic) FZLoginFailureBlock loginFailureBlock;
@property (copy, nonatomic) FZLoginCancelBlock loginCancelBlock;
    //中间转换的登录控制器
@property (strong, nonatomic) FZLoginViewController * tempLoginVC;

@property (assign, nonatomic) BOOL isHoldingPayment;

@end

@implementation SRLoginManager

+ (instancetype)sharedManager {
    static id sharedManager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[self alloc] init];
    });
    return sharedManager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
            //        _currentUser = [[SRLoginUser alloc] init];
        
    }
    return self;
}

#pragma mark - Public method

+ (BOOL)handelOpenURL:(NSURL *)url {
    
    SRLoginManager *shareManager = [SRLoginManager sharedManager];
    
    return [TencentOAuth HandleOpenURL:url] ||
    [WXApi handleOpenURL:url delegate:shareManager] ||
    [QQApiInterface handleOpenURL:url delegate:shareManager] ||
    [WeiboSDK handleOpenURL:url delegate:shareManager];
    
    return NO;
}

- (BOOL)hasLogin {
    if ([SRLoginUser userID] && [SRLoginUser authToken]) {
        return YES;
    }
    return NO;
}

- (void)logout {
    [self clear];
}

- (void)setHoldingPaymentStatus:(BOOL)holding {
    self.isHoldingPayment = holding;
}

- (BOOL)getHoldingPaymentStatus {
    return self.isHoldingPayment;
}

- (void)refreshVIPStatus {
    NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
    [param setValue:[SRLoginUser userID] forKey:@"member_id"];
    
//    [[[FZPersonCenterService alloc] init] getUserInfoWithParams:param success:^(NSInteger statusCode, NSString *message, id dataObject) {
//        if (statusCode == kFZRequestStatusCodeSuccess) {
//            FZOtherPersonHomePagePersonModel *model = dataObject;
//            
//            [SRLoginUser setVIPStatus:[NSString stringWithFormat:@"%ld", (long)model.isVIP]];
//            [SRLoginUser setVIPEndTime:model.vipEndTime];
//        } else {
//            FZLog(message);
//        }
//    } failure:^(id responseObject, NSError *error) {
//        FZLog(@"network error");
//    }];
}

/**
 *  4.60版本第一次启动时强制退出
 */
- (void)forceLogoutByFristLoadApp{
    NSString *string = [NSString stringWithFormat:@"forceLogoutByFristLoadApp%@",@"4.60"];
    if(![[NSUserDefaults standardUserDefaults] objectForKey:string]){
        [[NSUserDefaults standardUserDefaults] setObject:string forKey:string];
        [[NSUserDefaults standardUserDefaults] synchronize];
        if([self hasLogin]){
            [self logout];
        }
    }
}

- (void)clear {
    [SRLoginUser setUserID:nil];
    [SRLoginUser setCommonUId:nil];
    [SRLoginUser setNickname:nil];
    [SRLoginUser setAvatar:nil];
    [SRLoginUser setEmail:nil];
    [SRLoginUser setType:nil];
    [SRLoginUser setSchoolGrade:nil];
    
    [SRLoginUser setPeiyinNumber:nil];
    [SRLoginUser setPeiyinRank:nil];
    [SRLoginUser setAuthToken:nil];
    [SRLoginUser setUploadToken:nil];
    [SRLoginUser setUploadVideoToken:nil];
    
    [SRLoginUser setRongToken:nil];
    [SRLoginUser setUploadMessageToken:nil];
    [SRLoginUser setUploadPicToken:nil];
    [SRLoginUser setMessageLogURL:nil];
    
        //detail info
    [SRLoginUser setCover:nil];
    [SRLoginUser setArea:nil];
    [SRLoginUser setMobile:nil];
    [SRLoginUser setSchool:nil];
    [SRLoginUser setSchoolName:nil];
    
    [SRLoginUser setBirthday:nil];
    [SRLoginUser setSex:0];
    [SRLoginUser setSignature:nil];
    [SRLoginUser setCampus:nil];
    [SRLoginUser setUserClass:nil];
    
    [SRLoginUser setUserClassList:nil];
    [SRLoginUser setTeacherID:nil];
    [SRLoginUser setImageURL:nil];
    [SRLoginUser setSchoolIdentity:SRSchoolClassUserTypeNone];
    
    [SRLoginUser setUserSchoolInfoUserIdentity:-1];
    [SRLoginUser setUserStationInfoUserIdentity:-1];
    
    [SRLoginUser setSchoolID:nil];
}

- (void)updateUserInfo:(NSDictionary *)userInfo {
    
    if (!userInfo || ![userInfo isKindOfClass:[NSDictionary class]]) {
        return;
    }
    
    
    [SRLoginUser setUserID:userInfo[@"uid"]];
    [SRLoginUser setCommonUId:userInfo[@"uc_id"]];
    
    [SRLoginUser setNickname:userInfo[@"nickname"]];
    [SRLoginUser setAvatar:userInfo[@"avatar"]];
    [SRLoginUser setEmail:userInfo[@"email"]];
    [SRLoginUser setType:userInfo[@"type"]];
//    年级 1-12
    [SRLoginUser setSchoolGrade:userInfo[@"grade"]];
    [SRLoginUser setSchoolID:userInfo[@"school_id"]];
    
    [SRLoginUser setVIPStatus:userInfo[@"is_vip"]];
    [SRLoginUser setVIPEndTime:userInfo[@"vip_endtime"]];
    [SRLoginUser setVIPRights:userInfo[@"vip_power"]];
    
    [SRLoginUser setPeiyinRank:[NSString stringWithFormat:@"%@", userInfo[@"rank"]]];
    [SRLoginUser setAuthToken:userInfo[@"auth_token"]];
    [SRLoginUser setRongToken:userInfo[@"rong_token"]];
    
    [SRLoginUser setRefreshToken:userInfo[@"refresh_token"]];
    [SRLoginUser setAuthTokenExpire:userInfo[@"endtime"]];
    
    
    [SRLoginUser setUploadToken:userInfo[@"upload_token"]];
    [SRLoginUser setUploadVideoToken:userInfo[@"video_upload_token"]];
    
    [SRLoginUser setUploadMessageToken:userInfo[@"upload_msgtoken"]];
    [SRLoginUser setUploadPicToken:userInfo[@"picture_token"]];
    [SRLoginUser setMessageLogURL:userInfo[@"msglog_url"]];
    
        //detail info
    [SRLoginUser setCover:userInfo[@"cover"]];
    [SRLoginUser setArea:userInfo[@"area"]];
    [SRLoginUser setMobile:userInfo[@"mobile"]];
    [SRLoginUser setSchool:userInfo[@"school"]];
    [SRLoginUser setSchoolName:userInfo[@"school"]];
    [SRLoginUser setAvatarPrefix:@"http://7u2nh5.com2.z0.glb.qiniucdn.com/"];
    if (userInfo[@"mobile"]) {
        [SRLoginUser setLastUserName:userInfo[@"mobile"]];
    }
    
    [SRLoginUser setBirthday:userInfo[@"birthday"]];
    
    NSString *sexString = userInfo[@"sex"];
    if (sexString) {
        NSInteger sexInt = [sexString integerValue];
        [SRLoginUser setSex:sexInt];
    } else {
        [SRLoginUser setSex:0];
    }
    
    NSString *ageString = userInfo[@"age"];
    if (ageString) {
        NSInteger age = [ageString integerValue];
        [SRLoginUser setAge:age];
    } else {
        [SRLoginUser setAge:0];
    }

    
    
//    [SRLoginUser setSignature:userInfo[@"signature"]];
//    [SRLoginUser setCampus:userInfo[@"campus"]];
//    [SRLoginUser setUserClass:userInfo[@"class"]];
//    
//    [SRLoginUser setUserClassList:userInfo[@"class_list"]];
//    [SRLoginUser setTeacherID:userInfo[@"tch_id"]];
//    [SRLoginUser setImageURL:userInfo[@"img_url"]];
//    
//    [SRLoginUser setUserStationInfoUserIdentity:[userInfo[@"station"] integerValue]];
//    [SRLoginUser setUserSchoolInfoUserIdentity:[userInfo[@"typeid"] integerValue]];
    
    NSString *schoolIdentityString = userInfo[@"user_type"];
    if (schoolIdentityString) {
        NSInteger schoolIdentityInt = [schoolIdentityString integerValue];
        [SRLoginUser setSchoolIdentity:schoolIdentityInt];
    } else {
        [SRLoginUser setSchoolIdentity:SRSchoolClassUserTypeNone];
    }
    
}


- (void)modifyUserBasicInfo:(NSDictionary *)userInfo {
    
    if (!userInfo || ![userInfo isKindOfClass:[NSDictionary class]]) {
        return;
    }
    
    [SRLoginUser setNickname:userInfo[@"nickname"]];
    [SRLoginUser setAvatar:userInfo[@"avatar"]];
    [SRLoginUser setSchool:userInfo[@"school"]];
    
    
        //    年级 1-12
    [SRLoginUser setSchoolGrade:userInfo[@"grade"]];
    NSString *sexString = userInfo[@"sex"];
    if (sexString) {
        NSInteger sexInt = [sexString integerValue];
        [SRLoginUser setSex:sexInt];
    } else {
        [SRLoginUser setSex:0];
    }
    
    NSString *ageString = userInfo[@"age"];
    if (ageString) {
        NSInteger age = [ageString integerValue];
        [SRLoginUser setAge:age];
    } else {
        [SRLoginUser setAge:0];
    }
    
    [SRLoginUser setSchoolID:userInfo[@"school_id"]];
    
    NSString *schoolIdentityString = userInfo[@"user_type"];
    if (schoolIdentityString) {
        NSInteger schoolIdentityInt = [schoolIdentityString integerValue];
        [SRLoginUser setSchoolIdentity:schoolIdentityInt];
    } else {
        [SRLoginUser setSchoolIdentity:SRSchoolClassUserTypeNone];
    }
}


- (void)showLoginViewControllerFromViewController:(UIViewController *)fromViewController
                                 showCancelButton:(BOOL)showCancel
                                          success:(FZLoginSuccessBlock)success
                                          failure:(FZLoginFailureBlock)failure
                                           cancel:(FZLoginCancelBlock)cancelBlock{
    
    if (!fromViewController) {
        if (cancelBlock) {
            cancelBlock();
        }
        return;
    }
    self.loginSuccessBlock = success;
    self.loginFailureBlock = failure;
    self.loginCancelBlock = cancelBlock;
    if (self.tempLoginVC)
    {
        self.tempLoginVC = nil;
    }
    WEAKSELF
    FZLoginViewController *viewController = [[FZLoginViewController alloc] initWithNibName:@"FZLoginViewController" bundle:nil];
    viewController.showCancelButton = showCancel;
    viewController.loginSuccessBlock = ^(void) {
//        AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//        [appdelegate loginSuccess];
    };
    
    viewController.loginCancelBlock = ^(void)
    {
        STRONGSELFFor(weakSelf)
        if (strongSelf.loginCancelBlock) {
            strongSelf.loginCancelBlock();
        }
    };
    viewController.loginFailureBlock = ^(NSString *message) {
        [weakSelf didLoginFailure:message];
    };
    
    if (fromViewController.navigationController) {
        fromViewController.hidesBottomBarWhenPushed = YES;
        [fromViewController.navigationController pushViewController:viewController animated:YES];
    } else {
        FZNavigationController *loginNavigationController = [[FZNavigationController alloc] initWithRootViewController:viewController];
        fromViewController.hidesBottomBarWhenPushed = YES;
        [fromViewController presentViewController:loginNavigationController animated:YES completion:nil];
    }
    
    self.loginViewController = viewController;
}
/**
 *  显示登录页面
 */
- (void)showLoginViewSinceController:(UIViewController *)vc
{
    if (self.loginSuccessBlock)
    {
        self.loginSuccessBlock = nil;
    }
    if (self.loginViewController)
    {
        self.loginViewController = nil;
    }
    FZLoginViewController *viewController = [[FZLoginViewController alloc] initWithNibName:@"FZLoginViewController" bundle:nil];
    viewController.loginSuccessBlock = ^(void) {
        AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [appdelegate loginSuccess];
    };
    __block FZLoginViewController * weakLoginVC = viewController;
    viewController.loginFailureBlock = ^(NSString *errorMessage) {
        [weakLoginVC showHUDHintWithText:errorMessage];
    };
    viewController.hidesBottomBarWhenPushed = YES;
    [vc.navigationController pushViewController:viewController animated:YES];
    self.tempLoginVC = viewController;
}
- (void)showLoginViewControllerFromWindow:(UIWindow *)window
                         showCancelButton:(BOOL)showCancel
                                  success:(FZLoginSuccessBlock)success
                                  failure:(FZLoginFailureBlock)failure
                                   cancel:(FZLoginCancelBlock)cancel{
    self.loginSuccessBlock = success;
    self.loginFailureBlock = failure;
    self.loginCancelBlock = cancel;
    if (self.tempLoginVC)
    {
        self.tempLoginVC = nil;
    }
    WEAKSELF
    FZLoginViewController *viewController = [[FZLoginViewController alloc] initWithNibName:@"FZLoginViewController" bundle:nil];
    viewController.showCancelButton = showCancel;
    viewController.loginTip = self.loginTip;
    
    viewController.loginSuccessBlock = ^(void) {
        [weakSelf didLoginSuccess];
    };
    
    viewController.loginCancelBlock = ^(void) {
        STRONGSELFFor(weakSelf)
        if (strongSelf.loginCancelBlock) {
            strongSelf.loginCancelBlock();
        }
        
    };
    viewController.loginFailureBlock = ^(NSString *message) {
        [weakSelf didLoginFailure:message];
    };
    
    self.loginViewController = viewController;
    
    FZNavigationController *loginNavigationController = [[FZNavigationController alloc] initWithRootViewController:viewController];
    window.rootViewController = loginNavigationController;
}

- (BOOL)currentControllerIsLoginViewController:(UIWindow*)window{
    
    if(!window || !self.loginViewController){
        return NO;
    }
    
    if(![window.rootViewController isKindOfClass:[FZNavigationController class]]){
        return NO;
    }
    
    FZNavigationController *navigationController = (FZNavigationController*)window.rootViewController;
    
    if(self.loginViewController == [navigationController.viewControllers objectAtIndex:0]){
        return YES;
    }
    
    return NO;
}

#pragma mark - QQ Login

- (void)onQQLogin {
        //    NSMutableArray *qqPermissions =[NSMutableArray arrayWithObjects:
        //                                    kOPEN_PERMISSION_GET_USER_INFO,
        //                                    kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
        //                                    kOPEN_PERMISSION_ADD_ALBUM,
        //                                    kOPEN_PERMISSION_ADD_IDOL,
        //                                    kOPEN_PERMISSION_ADD_ONE_BLOG,
        //                                    kOPEN_PERMISSION_GET_INFO,
        //                                    kOPEN_PERMISSION_GET_OTHER_INFO,
        //                                    kOPEN_PERMISSION_GET_REPOST_LIST,
        //                                    kOPEN_PERMISSION_UPLOAD_PIC,
        //                                    kOPEN_PERMISSION_GET_VIP_INFO,
        //                                    kOPEN_PERMISSION_GET_VIP_RICH_INFO,
        //                                    kOPEN_PERMISSION_GET_INTIMATE_FRIENDS_WEIBO,
        //                                    kOPEN_PERMISSION_MATCH_NICK_TIPS_WEIBO,
        //                                    nil];
    NSArray* permissions = [NSArray arrayWithObjects:
                            kOPEN_PERMISSION_GET_USER_INFO,
                            kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                            kOPEN_PERMISSION_ADD_ALBUM,
                            kOPEN_PERMISSION_ADD_IDOL,
                            kOPEN_PERMISSION_ADD_ONE_BLOG,
                            kOPEN_PERMISSION_ADD_PIC_T,
                            kOPEN_PERMISSION_ADD_SHARE,
                            kOPEN_PERMISSION_ADD_TOPIC,
                            kOPEN_PERMISSION_CHECK_PAGE_FANS,
                            kOPEN_PERMISSION_DEL_IDOL,
                            kOPEN_PERMISSION_DEL_T,
                            kOPEN_PERMISSION_GET_FANSLIST,
                            kOPEN_PERMISSION_GET_IDOLLIST,
                            kOPEN_PERMISSION_GET_INFO,
                            kOPEN_PERMISSION_GET_OTHER_INFO,
                            kOPEN_PERMISSION_GET_REPOST_LIST,
                            kOPEN_PERMISSION_LIST_ALBUM,
                            kOPEN_PERMISSION_UPLOAD_PIC,
                            kOPEN_PERMISSION_GET_VIP_INFO,
                            kOPEN_PERMISSION_GET_VIP_RICH_INFO,
                            kOPEN_PERMISSION_GET_INTIMATE_FRIENDS_WEIBO,
                            kOPEN_PERMISSION_MATCH_NICK_TIPS_WEIBO,
                            nil];
    self.tencentOAuth = [[TencentOAuth alloc] initWithAppId:kQQAPPID andDelegate:self];
    [self.tencentOAuth authorize:permissions inSafari:NO];
}

#pragma mark - TencentLoginDelegate

- (void)tencentDidLogin {
        // 登录成功
    BOOL bSuccess = [self.tencentOAuth getUserInfo];
    if (!bSuccess) {
        [self didLoginFailure:nil];
    } else {
        [self showLoadingView];
    }
}

- (void)tencentDidNotLogin:(BOOL)cancelled {
    NSString *errorMessage = nil;
    if (cancelled) {
        errorMessage = @"登录取消";
    }
    [self didLoginFailure:errorMessage];
}

-(void)tencentDidNotNetWork {
    [self didLoginFailure:nil];
}

-(void)tencentDidLogout {
    
}

    //获取qq用户信息
- (void)getUserInfoResponse:(APIResponse *)response {
    if (response.retCode != 0) {
            //获取失败
        [self didLoginFailure:nil];
        return;
    }
    
    NSString *accessToken = self.tencentOAuth.accessToken;
    NSDictionary *responseObject = response.jsonResponse;
    
    NSString *token = self.tencentOAuth.openId;
    NSString *nickname = responseObject[@"nickname"];
    NSString *avatar = responseObject[@"figureurl_qq_2"];
    
    NSString *sexString = responseObject[@"gender"];
    NSString *sex = @"0";
    if ([sexString isEqualToString:@"男"]) {
        sex = @"1";
    } else if ([sexString isEqualToString:@"女"]) {
        sex = @"2";
    }
    
    NSString *deviceToken = [self uniqID];
    NSString *authURL = [NSString stringWithFormat:@"https://graph.qq.com/user/get_user_info?oauth_consumer_key=%@&access_token=%@&openid=%@&format=json", kQQAPPID, accessToken, token];
    
    NSMutableDictionary *params = [@{} mutableCopy];
    [params setValue:token forKey:@"token"];
    [params setValue:@(1) forKey:@"type"];
    [params setValue:nickname forKey:@"nickname"];
    [params setValue:avatar forKey:@"avatar"];
    [params setValue:sex forKey:@"sex"];
    [params setValue:deviceToken forKey:@"devicetoken"];
    [params setValue:authURL forKey:@"auth_url"];
    [self thirdLoginWithParams:params];
}

- (void)isOnlineResponse:(NSDictionary *)response {
        //qq在线状态
}

#pragma mark - SinaWeiboDelegate

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response {
    if([response isKindOfClass:[WBSendMessageToWeiboResponse class]]){
            //分享
    }else if ([response isKindOfClass:[WBAuthorizeResponse class]]){
        if(response.statusCode == WeiboSDKResponseStatusCodeSuccess){
                //授权成功
            WBAuthorizeResponse *authResponse = (WBAuthorizeResponse *)response;
            NSString *accessToken = authResponse.accessToken;
            NSString *openID = authResponse.userID;
            
            [self showLoadingView];
            [self querySinaWeiboUserInfoWithAccessToken:accessToken openID:openID];
        }else if (response.statusCode == WeiboSDKResponseStatusCodeUserCancel){
            [self didLoginFailure:@"登录取消"];
        } else {
            [self didLoginFailure:nil];
        }
    }
}

- (void)didReceiveWeiboRequest:(WBBaseRequest *)request {
        //    NSLog(@"收到微博请求");
}

- (void)querySinaWeiboUserInfoWithAccessToken:(NSString *)accessToken openID:(NSString *)openID {
        //根据用户ID获取用户信息
    NSString *requestString = [NSString stringWithFormat:@"https://api.weibo.com/2/users/show.json?uid=%@&access_token=%@", openID,accessToken];
    WEAKSELF
    [[SRNetWorkManager sharedInstance] GETFromThirdServerWithUrl:requestString parameters:nil responseDtoClassType:nil success:^(id responseObject)  {
            //获取accessToken 之后，需要获取用户信息
        if (!responseObject) {
                //错误
            [weakSelf didLoginFailure:nil];
        } else {
            NSString *nickname = responseObject[@"name"];
            NSString *avatar = responseObject[@"avatar_hd"];
            
            NSString *sexString = responseObject[@"gender"];
            NSString *sex = @"0";
            if ([sexString isEqualToString:@"f"]) {
                sex = @"2";
            } else if ([sexString isEqualToString:@"m"]){
                sex = @"1";
            }
            
            NSString *deviceToken = [weakSelf uniqID];
            NSString *preWeiboID = [NSString stringWithFormat:@"funpeiyin%@", openID];
            NSString *weiboID = [preWeiboID MD5Hash];
            
            NSMutableDictionary *params = [@{} mutableCopy];
            [params setValue:weiboID forKey:@"token"];
            [params setValue:@(2) forKey:@"type"];
            [params setValue:nickname forKey:@"nickname"];
            [params setValue:avatar forKey:@"avatar"];
            [params setValue:sex forKey:@"sex"];
            [params setValue:deviceToken forKey:@"devicetoken"];
            [params setValue:requestString forKey:@"auth_url"];
            
            [weakSelf thirdLoginWithParams:params];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [weakSelf didLoginFailure:nil];
    }];
}


    //QQ 和 微信的回调方式一样
#pragma mark - WXApiDelegate && QQApiInterfaceDelegate <NSObject>

/**
 处理来至QQ的请求
 */
- (void)onReq:(id )req {
    if ([req isKindOfClass:[QQBaseReq class]]) {
            //qq 回调
    } else if ([req isKindOfClass:[BaseReq class]]) {
            //微信回调
    }
}

/**
 处理来至QQ的响应
 */
- (void)onResp:(id )resp {
    if ([resp isKindOfClass:[QQBaseResp class]]) {
            //qq回调
    } else if ([resp isKindOfClass:[SendAuthResp class]]) {
            //微信登录
        SendAuthResp *authResp = (SendAuthResp *)resp;
        if (authResp.errCode == 0) {
                //登录授权成功,然后可以获取用户信息
            [self showLoadingView];
            [self queryWeChatAccessTokenWithCode:authResp.code];
        } else {
            [self didLoginFailure:@"登录取消"];
        }
    }
}

    //1、通过code, 先获取accessToken；2、通过accessToken获取用户信息
- (void)queryWeChatAccessTokenWithCode:(NSString *)code {
    
    WEAKSELF
    NSString *requestString = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code", kWechatAPPKey, kWechatAPPSecret, code];
    
    [[SRNetWorkManager sharedInstance] GETFromThirdServerWithUrl:requestString parameters:nil responseDtoClassType:nil success:^(id responseObject) {
        NSString *errCode = responseObject[@"errcode"];
        if (errCode && [errCode integerValue] > 0) {
                //错误
            [weakSelf didLoginFailure:responseObject[@"errmsg"]];
        } else {
            NSString *accessToken = responseObject[@"access_token"];
            NSString *openID = responseObject[@"openid"];
            [weakSelf queryWeChatUserInfoWithAccessToken:accessToken openID:openID];
        }
        
    } failure:^(id responseObject, NSError *error) {
        [weakSelf  didLoginFailure:nil];
        
    }];
}

- (void)queryWeChatUserInfoWithAccessToken:(NSString *)accessToken openID:(NSString *)openID {
    WEAKSELF
    NSString *requestString = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@", accessToken, openID];
    
    [[SRNetWorkManager sharedInstance] GETFromThirdServerWithUrl:requestString parameters:nil responseDtoClassType:nil success:^(id responseObject){
            //获取accessToken 之后，需要获取用户信息
        NSString *errCode = responseObject[@"errcode"];
        if (errCode && [errCode integerValue] > 0) {
                //错误
            [weakSelf didLoginFailure:responseObject[@"errmsg"]];
        } else {
            NSString *token = responseObject[@"openid"];
            NSString *nickname = responseObject[@"nickname"];
            NSString *avatar = responseObject[@"headimgurl"];
            NSString *sex = responseObject[@"sex"];
            NSString *deviceToken = [weakSelf uniqID];
            NSString *authURL = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?qupeiyin=1&access_token=%@&openid=%@", accessToken, openID];
            
            NSMutableDictionary *params = [@{} mutableCopy];
            [params setValue:token forKey:@"token"];
            [params setValue:@(3) forKey:@"type"];
            [params setValue:nickname forKey:@"nickname"];
            [params setValue:avatar forKey:@"avatar"];
            [params setValue:sex forKey:@"sex"];
            [params setValue:deviceToken forKey:@"devicetoken"];
            [params setValue:authURL forKey:@"auth_url"];
            
            [weakSelf thirdLoginWithParams:params];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [weakSelf  didLoginFailure:nil];
        
    } ];
}

#pragma mark - Private Method

- (void)didLoginSuccess {
    [self.loginViewController stopProgressHUD];
    if (self.loginSuccessBlock) {
        self.loginSuccessBlock();
    }
	
//	[self uploadJPushRegisterID];
	
}

- (void)didLoginFailure:(NSString *)message {
    if (self.tempLoginVC)
    {
        [self.tempLoginVC stopProgressHUD];
    }
    [self.loginViewController stopProgressHUD];
    if (!message) {
        message = @"登录失败";
    }
    [self.loginViewController showHUDErrorMessage:message];
    
    if (self.loginFailureBlock) {
        self.loginFailureBlock(message);
    }
}

- (void)showLoadingView {
    [self.tempLoginVC startProgressHUDWithText:@"正在登录..."];
    [self.loginViewController startProgressHUDWithText:@"正在登录..."];
}

- (void)thirdLoginWithParams:(NSMutableDictionary *)parameters {
    WEAKSELF
    NSString *requestString = [[SRAPICreater sharedInstance] APIWithName:@"user_third_login"];
    
    NSString *jsonStr = [FCUtil getDeviceInfoJsonString];
    [parameters setValue:jsonStr forKey:@"device_info"];
    
    [[SRNetWorkManager sharedInstance] POSTNODefaultParamWithUrl:requestString parameters:parameters responseClass:nil success:^(NSInteger statusCode, NSString *message, id dataObject) {
        if (statusCode == kFZRequestStatusCodeSuccess) {
            
            NSNumber *type = parameters[@"type"];
            if ([type integerValue] == 1) {
                [self saveLoginSuccessType:@"QQ登录"];
            } else if ([type integerValue] == 2) {
                [self saveLoginSuccessType:@"微博登录"];
            } else if ([type integerValue] == 3) {
                [self saveLoginSuccessType:@"微信登录"];
            }
            
            [weakSelf updateUserInfo:dataObject];
            AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                STRONGSELFFor(weakSelf)
                if (strongSelf.tempLoginVC)
                {
                        //
                    [appdelegate loginSuccess];
                        //返回到上一个页面
                    [strongSelf.tempLoginVC.navigationController popViewControllerAnimated:NO];
                }
                if (strongSelf.loginViewController) {
                        //返回到上一个页面
                    [strongSelf.loginViewController.navigationController popViewControllerAnimated:NO];
                }
            });
            [weakSelf didLoginSuccess];
        } else {
            [weakSelf didLoginFailure:message];
        }
    } failure:^(id responseObject, NSError *error) {
        [weakSelf didLoginFailure:nil];
    }];
}

- (void)saveLoginSuccessType:(NSString *)typeString {
//    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    [userDefaults setValue:typeString forKey:kLastLoginUserDefaultsKey];
//    [userDefaults synchronize];
}

- (void)queryBasicUrlWithSuccess:(FZSuccessBlock)success failure:(FZFailureBlock)failure {
    WEAKSELF
    NSString *urlString = [[SRAPICreater sharedInstance] APIWithName:@"basic_html5"];
    [[SRNetWorkManager sharedInstance] GET:urlString needCache:NO parameters:nil responseClass:[FZBasicURLModel class] success:^(NSInteger statusCode, NSString *message, id dataObject) {
        
        if (statusCode == kFZRequestStatusCodeSuccess && dataObject) {
            FZBasicURLModel *urlModel = dataObject;
            weakSelf.basicURLModel = urlModel;
        }
        
        if (success) {
            success(statusCode, message, dataObject);
        }
        
    } failure:^(id responseObject, NSError *error) {
        if (failure) {
            failure(responseObject, error);
        }
    }];
}



- (void)updateUserInfoFromNetwork
{
    NSString *urlString = [[SRAPICreater sharedInstance] APIWithName:@"user_member_data"];
    [[SRNetWorkManager sharedInstance] GET:urlString needCache:NO parameters:nil responseClass:nil success:^(NSInteger statusCode, NSString *message, id dataObject) {
        if (statusCode == kFZRequestStatusCodeSuccess) {
            [SRLoginUser setUploadPicToken:dataObject[@"upload_pictoken"]];
        }
    } failure:^(id responseObject, NSError *error) {
        
    }];
}

- (NSString *)uniqID {
    NSString* uniqueIdentifier = kUniqueIdentifier;
    return uniqueIdentifier;
}

- (NSString *)schoolGrade {
        //初始化年级数据和视图
    NSArray *gradeArray = @[@"一年级",@"二年级",@"三年级",@"四年级",@"五年级",@"六年级",@"七年级",@"八年级",@"九年级"];
    NSString *gradeIndexString = [SRLoginUser schoolGrade];
    NSInteger gradeIndex = -1;
    if (gradeIndexString) {
        gradeIndex = [gradeIndexString integerValue] - 1;
    }
    
    if (gradeIndex >= 0 && gradeIndex < [gradeArray count] ) {
        return [gradeArray objectAtIndex:gradeIndex];
    } else {
        return nil;
    }
}

- (void)uploadJPushRegisterID {
	NSString *registerID = [JPUSHService registrationID];

	NSLog(@"****uploadJPushRegisterID: %@", registerID);
	
	if (!registerID) {
		return;
	}
	
	NSString *urlString = [[SRAPICreater sharedInstance] APIWithName:@"user_pushinfo"];
	NSMutableDictionary *params = [NSMutableDictionary dictionary];
	[params setValue:registerID forKey:@"registration_id"];
	
	[[SRNetWorkManager sharedInstance] POST:urlString needCache:NO parameters:params responseClass:nil success:^(NSInteger statusCode, NSString *message, id dataObject) {
		if (statusCode) {
			
		}
	} failure:^(id responseObject, NSError *error) {
		
	}];
	
}


@end
